package com.itheima.advantagesup.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.advantagesup.common.BaseContext;
import com.itheima.advantagesup.common.R;
import com.itheima.advantagesup.common.constant.LoginConstant;
import com.itheima.advantagesup.properties.JwtProperties;
import com.itheima.advantagesup.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * LoginHandlerInterceptor
 *
 * @author liliudong
 * @version 1.0
 * @description
 * @date 2023/7/26 17:03
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LoginHandlerInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;

    private final JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(jwtProperties.getHeader());
        if (StringUtils.isEmpty(token)) {
            return err(response);
        }
        try {
            Claims claims = jwtUtil.parseJWT(token);
            String userId = claims.get(LoginConstant.USER_ID, String.class);
            BaseContext.setLoginUserId(userId);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return err(response);
        }
    }

    /**
     * 异常情况
     *
     * @param response 响应
     * @return boolean
     * @throws IOException ioexception
     */
    private static boolean err(HttpServletResponse response) throws IOException {
        R<?> error = R.error(9997, "登陆验证失败，请重新登陆！");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        response.getWriter().write(JSON.toJSONString(error));
        return false;
    }
}
